import 'package:flutter/material.dart';
import "package:eventsource/eventsource.dart";
import 'dart:convert';

void main() async {
  runApp(SampleApp());
}

class SampleApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sample App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  List<Map<String, dynamic>> listOfColumns = [];

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  _loadData() async {
    EventSource eventSource =
      await EventSource.connect("http://10.213.20.43:9910/msi/mainTableInfo");

    // listen for events
    eventSource.listen((Event event) {
      setState(() {
        String data = "${event.data}";
        print(data);
        print(json.decode(data));
        listOfColumns.add(json.decode(data));
        print(listOfColumns.length);
      });
    });
  }

  DataRow _getDataRow(data) {
    return DataRow(
      cells: <DataCell>[
        DataCell(Text(data["fileName"])),
        DataCell(Text(data["startTime"])),
        DataCell(Text(data["endTime"])),
        DataCell(Text(data["status"])),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('文件列表'),
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: new ListView(
          children: <Widget>[
            new DataTable(
              columns: [
                DataColumn(label: Text('File')),
                DataColumn(label: Text('Start')),
                DataColumn(label: Text('End')),
                DataColumn(label: Text('Status')),
              ],
              rows: List.generate(listOfColumns.length,
                      (index) => _getDataRow(listOfColumns[index])),
            )
          ],
        ),
      ),
    );
  }
}
